﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DomainModel.Abstract;
using DomainModel.Entities;
using System.Data.Linq;

namespace DomainModel.Concrete
{
    public class SqlPositionsRepository : IPositionsRepository
    {
        private Table<Position> positionsTable;

        public SqlPositionsRepository(string connectionString)
        {
            positionsTable = new DataContext(connectionString).GetTable<Position>();
        }

        public IQueryable<Position> Positions
        {
            get { return positionsTable; }
        }

        public void SavePosition(Position position)
        {
            if (position.PositionID == 0)
            {
                //It's a new position
                positionsTable.InsertOnSubmit(position);
            }
            else
            {
                //It's an existing position
                positionsTable.Attach(position);

                //Tell DataContext to detect any changes since last save
                positionsTable.Context.Refresh(RefreshMode.KeepCurrentValues, position);
            }

            //Submit the changes
            positionsTable.Context.SubmitChanges();
        }

        public void DeletePosition(Position position)
        {
            positionsTable.DeleteOnSubmit(position);
            positionsTable.Context.SubmitChanges();
        }
    }
}
